/**
 * 自定义图片加载器
 * 用于优化图片加载和处理不同的图片源
 */

export interface ImageLoaderProps {
  src: string;
  width: number;
  quality?: number;
}

/**
 * 默认图片加载器
 */
export default function imageLoader({
  src,
  width,
  quality,
}: ImageLoaderProps): string {
  // 如果是相对路径，直接返回
  if (src.startsWith('/')) {
    return src;
  }

  // 如果是完整的URL，进行优化处理
  if (src.startsWith('http')) {
    return optimizeExternalImage(src, width, quality);
  }

  // 默认返回原始src
  return src;
}

/**
 * 优化外部图片
 */
function optimizeExternalImage(
  src: string,
  width: number,
  quality = 75
): string {
  // 处理Trae API图片
  if (src.includes('trae-api-us.mchost.guru')) {
    return optimizeTraeApiImage(src, width, quality);
  }

  // 处理Unsplash图片
  if (src.includes('unsplash.com')) {
    return optimizeUnsplashImage(src, width, quality);
  }

  // 处理Pexels图片
  if (src.includes('pexels.com')) {
    return optimizePexelsImage(src, width, quality);
  }

  // 其他外部图片直接返回
  return src;
}

/**
 * 优化Trae API图片
 */
function optimizeTraeApiImage(
  src: string,
  width: number,
  quality: number
): string {
  try {
    const url = new URL(src);

    // 设置宽度
    url.searchParams.set('w', width.toString());

    // 设置质量
    url.searchParams.set('q', quality.toString());

    // 设置格式为WebP（如果支持）
    if (supportsWebP()) {
      url.searchParams.set('f', 'webp');
    }

    return url.toString();
  } catch (error) {
    console.warn('Failed to optimize Trae API image:', error);
    return src;
  }
}

/**
 * 优化Unsplash图片
 */
function optimizeUnsplashImage(
  src: string,
  width: number,
  quality: number
): string {
  try {
    const url = new URL(src);

    // Unsplash参数
    url.searchParams.set('w', width.toString());
    url.searchParams.set('q', quality.toString());
    url.searchParams.set('fm', 'webp');
    url.searchParams.set('fit', 'crop');
    url.searchParams.set('crop', 'smart');

    return url.toString();
  } catch (error) {
    console.warn('Failed to optimize Unsplash image:');
    return src;
  }
}

/**
 * 优化Pexels图片
 */
function optimizePexelsImage(src: string, width: number): string {
  try {
    const url = new URL(src);

    // Pexels参数
    url.searchParams.set('w', width.toString());
    url.searchParams.set('h', 'auto');
    url.searchParams.set('fit', 'crop');
    url.searchParams.set('crop', 'smart');

    return url.toString();
  } catch (error) {
    console.warn('Failed to optimize Pexels image:');
    return src;
  }
}

/**
 * 检测WebP支持
 */
function supportsWebP(): boolean {
  if (typeof window === 'undefined') return false;

  try {
    const canvas = document.createElement('canvas');
    canvas.width = 1;
    canvas.height = 1;
    return canvas.toDataURL('image/webp').indexOf('data:image/webp') === 0;
  } catch (error) {
    return false;
  }
}

/**
 * 检测AVIF支持
 */
function supportsAVIF(): boolean {
  if (typeof window === 'undefined') return false;

  try {
    const canvas = document.createElement('canvas');
    canvas.width = 1;
    canvas.height = 1;
    return canvas.toDataURL('image/avif').indexOf('data:image/avif') === 0;
  } catch (error) {
    return false;
  }
}

/**
 * 获取最佳图片格式
 */
export function getBestImageFormat(): 'avif' | 'webp' | 'jpeg' {
  if (supportsAVIF()) return 'avif';
  if (supportsWebP()) return 'webp';
  return 'jpeg';
}

/**
 * 生成响应式图片URL
 */
export function generateResponsiveImageUrls(
  src: string,
  sizes: number[],
  quality = 75
): Array<{ src: string; width: number }> {
  return sizes.map(width => ({
    src: imageLoader({ src, width, quality }),
    width,
  }));
}

/**
 * 预加载图片
 */
export function preloadImage(src: string, priority = false): Promise<void> {
  return new Promise((resolve, reject) => {
    const link = document.createElement('link');
    link.rel = priority ? 'preload' : 'prefetch';
    link.as = 'image';
    link.href = src;

    link.onload = () => resolve();
    link.onerror = () => reject(new Error(`Failed to preload image: ${src}`));

    document.head.appendChild(link);
  });
}

/**
 * 批量预加载图片
 */
export function preloadImages(
  srcs: string[],
  priority = false
): Promise<void[]> {
  return Promise.all(srcs.map(src => preloadImage(src, priority)));
}

/**
 * 图片加载性能监控
 */
export function trackImageLoadPerformance(
  src: string,
  startTime: number
): void {
  const loadTime = performance.now() - startTime;

  // 发送性能数据到分析服务
  if (typeof window !== 'undefined' && 'gtag' in window) {
    (
      window as Window & {
        gtag: (
          event: string,
          action: string,
          params: Record<string, unknown>
        ) => void;
      }
    ).gtag('event', 'image_load_time', {
      event_category: 'Performance',
      event_label: src,
      value: Math.round(loadTime),
    });
  }

  // 控制台输出（开发环境）
  if (process.env.NODE_ENV === 'development') {
    console.log(`Image loaded in ${loadTime.toFixed(2)}ms:`, src);
  }
}

/**
 * 图片错误处理
 */
export function handleImageError(src: string, error: Error): string {
  console.warn(`Failed to load image: ${src}`, error);

  // 返回占位符图片
  return generatePlaceholderImage(400, 300, 'Image not found');
}

/**
 * 生成占位符图片
 */
export function generatePlaceholderImage(
  width: number,
  height: number,
  text = 'Image'
): string {
  const svg = `
    <svg width="${width}" height="${height}" xmlns="http://www.w3.org/2000/svg">
      <defs>
        <linearGradient id="grad" x1="0%" y1="0%" x2="100%" y2="100%">
          <stop offset="0%" style="stop-color:#f3f4f6;stop-opacity:1" />
          <stop offset="100%" style="stop-color:#e5e7eb;stop-opacity:1" />
        </linearGradient>
      </defs>
      <rect width="100%" height="100%" fill="url(#grad)"/>
      <text x="50%" y="50%" font-family="Arial, sans-serif" font-size="16" 
            fill="#9ca3af" text-anchor="middle" dominant-baseline="middle">
        ${text}
      </text>
    </svg>
  `;

  return `data:image/svg+xml;base64,${btoa(svg)}`;
}

/**
 * 图片缓存策略
 */
export const IMAGE_CACHE_CONFIG = {
  // 缓存时间（秒）
  cacheTTL: {
    avatar: 60 * 60 * 24 * 7, // 7天
    thumbnail: 60 * 60 * 24 * 30, // 30天
    hero: 60 * 60 * 24 * 7, // 7天
    content: 60 * 60 * 24 * 30, // 30天
    static: 60 * 60 * 24 * 365, // 1年
  },

  // 预加载策略
  preload: {
    critical: true, // 关键图片立即预加载
    aboveFold: true, // 首屏图片预加载
    belowFold: false, // 非首屏图片懒加载
  },

  // 质量设置
  quality: {
    thumbnail: 70,
    small: 75,
    medium: 80,
    large: 85,
    hero: 90,
  },
} as const;
